package helpers;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Class to handle various hash encryptions
 * @author Jakub Macoun
 */
public class Hasher {
    
    /**
     * Encrpyts text using MD5
     * @param text  Text to encrypt
     * @return  MD5 hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String md5(String text) {
        return doHash(text, "MD5");
    }
    
    /**
     * Encrpyts text using SHA
     * @param text  Text to encrypt
     * @return  SHA hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String sha(String text) {
        return doHash(text, "SHA");
    }
    
    /**
     * Encrpyts text using SHA-1
     * @param text  Text to encrypt
     * @return  SHA-1 hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String sha1(String text) {
        return doHash(text, "SHA-1");
    }
    
    /**
     * Encrpyts text using SHA-384
     * @param text  Text to encrypt
     * @return  SHA-384 hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String sha384(String text) {
        return doHash(text, "SHA-384");
    }
    
    /**
     * Encrpyts text using SHA-256
     * @param text  Text to encrypt
     * @return  SHA-256 hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String sha256(String text) {
        return doHash(text, "SHA-256");
    }
    
    /**
     * Encrpyts text using SHA-512
     * @param text  Text to encrypt
     * @return  SHA-512 hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    public static String sha512(String text) {
        return doHash(text, "SHA-512");
    }
    
    /**
     * Encrypts text to hash form
     * @param text  Text to encrypt
     * @param algo  Algorythm to use
     * @return  Hash form of the text
     * @throws NoSuchAlgorithmException 
     */
    private static String doHash(String text, String algo) {
        try {
            MessageDigest md;
            md= MessageDigest.getInstance(algo);

            md.update(text.getBytes());
            byte[] mb = md.digest();
            String out = "";
            for (int i = 0; i < mb.length; i++) {
                byte temp = mb[i];
                String s = Integer.toHexString(new Byte(temp));
                while (s.length() < 2) {
                    s = "0" + s;
                }
                s = s.substring(s.length() - 2);
                out += s;
            }
            
            return out;
        } catch (Exception ex) {
            return null;
        }
    }
}